﻿using System;
using System.Threading;
using System.Web;

namespace StoneAge.Controller.AsyncHandler
{
    class AjaxAsyncResult : IAsyncResult
    {
        private AsyncCallback m_AsyncCallback = null;
        private ManualResetEvent m_Event = null;

        private HttpContext m_Context = null;
        public HttpContext Context { get { return m_Context; } }

        private object m_AsyncState = null;
        public object AsyncState
        {
            get { return m_AsyncState; }
            set { m_AsyncState = value; }
        }

        public WaitHandle AsyncWaitHandle
        {
            get
            {
                if (m_IsCompleted)
                    return null;

                if (m_Event == null)
                    m_Event = new ManualResetEvent(false);
                return m_Event;
            }
        }

        public bool CompletedSynchronously { get { return false; } }

        private volatile bool m_IsCompleted = false;
        public bool IsCompleted { get { return m_IsCompleted; } }

        public AjaxAsyncResult(HttpContext context, AsyncCallback callback)
        {
            m_Context = context;
            m_AsyncCallback = callback;
        }

        public void SetCompleted()
        {
            m_IsCompleted = true;

            ManualResetEvent waitEvent = Interlocked.CompareExchange(ref m_Event, null, null);
            if (null != waitEvent)
                waitEvent.Set();

            if (null != m_AsyncCallback)
                m_AsyncCallback(this);
        }
    }
}
